#!/bin/bash

# This script is based on AFNI and LayNii and SPM (in matlab)

# this section makes images compatible with oblique slices. It preserves the
# origin of the slab, so it will overlap with the structural data. 
# This step is not really needed, but it will later alignemnt easier
# This step requires ANFI version 25 or later
#for filename in S*.nii.gz
#do
#adjunct_deob_around_origin \
#    -input ${filename}     \
#    -prefix deob_${filename}    \
#    -write_aff_mats
#    -overwrite
#done

#generating motion mask
3dAutomask -prefix moma.nii.gz -peels 3 -dilate 2  S*_TI1*.nii.gz

# calculate mot alignment, with *solid body (6 DOF)*
idx=100
echo "loop for TI1 over PA (100) and AP (101), probably"

for filename in ./S*_TI1*.nii.gz
do
    echo $filename
    3dcopy $filename ./Basis_TI1_${idx}.nii -overwrite
    3dTstat -mean -prefix TI1_reference.nii.gz Basis_TI1_${idx}.nii'[1..2]' 

    3dAllineate                                                              \
        -1Dmatrix_save  ALLIN_TI1_${idx}.aff12.1D                            \
        -cost           lpa                                                  \
        -prefix         moco_Basis_TI1_${idx}.nii                            \
        -base           TI1_reference.nii.gz                                 \
        -source         Basis_TI1_${idx}.nii                                 \
        -weight         moma.nii.gz \
        -final          wsinc5

    idx=$(($idx+1))
done 



idx=100
echo "loop for TI2 over PA (100) and AP (101), probably"

for filename in ./S*_TI2*.nii.gz
do
    echo $filename
    3dcopy $filename ./Basis_TI2_${idx}.nii -overwrite
    3dTstat -mean -prefix TI2_reference.nii.gz Basis_TI2_${idx}.nii'[1..2]'

    3dAllineate                                                              \
        -1Dmatrix_save  ALLIN_TI2_${idx}.aff12.1D                            \
        -cost           lpa                                                  \
        -prefix         moco_Basis_TI2_${idx}.nii                            \
        -base           TI2_reference.nii.gz                                 \
        -source         Basis_TI2_${idx}.nii                                 \
        -weight         moma.nii.gz                                          \
        -final          wsinc5

    idx=$(($idx+1))
done 
